
# 2.3 线性代数

import torch

# 2.3.1. 标量
x = torch.tensor(3.0)
y = torch.tensor(2.0)
print(x+y)
print(x*y)
print(x/y)
print(x**y)
# 输出： tensor(5.)
# tensor(6.)
# tensor(1.5000)
# tensor(9.)


# 2.3.2. 向量
x = torch.arange(4)
print(x[3])
# 输出：tensor(3)

# 2.3.2.1. 长度、维度和形状
print(len(x))
print(x.shape)
# 输出：4
# torch.Size([4])  一维，长度为 4

# 2.3.3. 矩阵
A = torch.arange(20,dtype=torch.float32).reshape(4,5)
print(A)
# 输出：tensor([[ 0,  1,  2,  3,  4],
#         [ 5,  6,  7,  8,  9],
#         [10, 11, 12, 13, 14],
#         [15, 16, 17, 18, 19]])

# 转置
print(A.T)
# 输出：tensor([[ 0,  5, 10, 15],
#         [ 1,  6, 11, 16],
#         [ 2,  7, 12, 17],
#         [ 3,  8, 13, 18],
#         [ 4,  9, 14, 19]])

# 对称方阵
B = torch.tensor([[1,2,3],[2,0,4],[3,4,5]])
print(B == B.T)
# 输出：tensor([[True, True, True],
#         [True, True, True],
#         [True, True, True]])


# 2.3.4. 张量
x = torch.arange(24).reshape(2,3,4)
print(x)
# 输出：tensor([[[ 0,  1,  2,  3],
#          [ 4,  5,  6,  7],
#          [ 8,  9, 10, 11]],
#
#         [[12, 13, 14, 15],
#          [16, 17, 18, 19],
#          [20, 21, 22, 23]]])


# 2.3.5. 张量算法的基本性质
print(A.shape)
# 输出：torch.Size([4, 5])
print(A.sum())
# 输出：tensor(190)
print(A.sum(axis= 0))
# 输出：tensor([30, 34, 38, 42, 46])
print(A.sum(axis=[0,1]))
# 输出：tensor(190)
print(A.mean())
# tensor(9.5000)
print(A.sum()/A.numel())
# tensor(9.5000)
# A.numel()：计算元素总数
print(A.sum(dim=1))
# 输出：tensor([10., 35., 60., 85.])


# 2.3.6.1. 非降维求和
sum_A = A.sum(dim = 1,keepdim=True)
print(sum_A)
# 输出：tensor([[10.],
#         [35.],
#         [60.],
#         [85.]])

print(A/sum_A)
# 输出：tensor([[0.0000, 0.1000, 0.2000, 0.3000, 0.4000],
#         [0.1429, 0.1714, 0.2000, 0.2286, 0.2571],
#         [0.1667, 0.1833, 0.2000, 0.2167, 0.2333],
#         [0.1765, 0.1882, 0.2000, 0.2118, 0.2235]])

# 2.3.7. 点积
y = torch.ones(4,dtype=torch.float32)
x = torch.arange(4,dtype=torch.float32)
print(torch.dot(x,y))
# tensor(6.)
print(torch.sum(x*y))


# 2.3.8. 矩阵-向量积
y = y.reshape(1,4)
print(y.shape)
print(x.shape)
print(torch.mv(y,x))
# 输出：tensor([6.])


# 2.3.9. 矩阵-矩阵乘法
y = y.reshape(1,4)
x = x.reshape(4,1)
print(y.shape)
print(x.shape)
print(torch.mm(y,x))
# 输出：tensor([[6.]])


# 2.3.10. 范数
u = torch.tensor([3.0,-4.0])
print(torch.norm(u))
# tensor(5.)
print(torch.ones((4, 9)))
print(torch.norm(torch.ones((4, 9))))
# tensor(6.)








